from flask import Flask
from flask import render_template
from flask import jsonify
from flask import request
import os
import stat
import re
import settings

app = Flask(__name__)

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/_save_note', methods=['POST'])
def save_note():
    note_title = request.form['title']
    if note_title == '':
        return "error", 400
    note_text = request.form['text']
    note_filename = request.form['filename']
    if note_filename == '':
        note_filename = '%s%s' % (settings.notename(), settings.noteext)
    os.umask(1)
    with open(os.path.join(settings.notepath, re.sub(r'[^-a-zA-Z0-9_\.]+', '', note_filename)), "w") as f:
        f.write('%s\n' % note_title)
        f.write(note_text)
    return jsonify(result="success")

@app.route('/_get_note_list')
def get_note_list():
    notes = {}
    for entry in os.listdir(settings.notepath):
        if entry.endswith(settings.noteext) and os.path.isfile(os.path.join(settings.notepath, entry)):
            with open(os.path.join(settings.notepath, entry)) as f:
                notes[entry] = f.readline().strip()
    return jsonify(result=notes)

@app.route('/_get_note_text')
def get_note_text():
    note_text = ''
    note_filename = request.args.get('filename')
    if os.path.isfile(os.path.join(settings.notepath, note_filename)):
        with open(os.path.join(settings.notepath, note_filename)) as f:
            note_text = ''.join(f.readlines()[1:])
    return jsonify(result=note_text)

@app.route('/shutdown')
def shutdown():
    if settings.debug:
    	shutdown_server()
    	return 'Server shutting down...'
    return 'Nope!'

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host=settings.host, port=settings.port, debug=settings.debug)

